#include <ESP8266WiFi.h>
#include <string>

WiFiServer server(9527);
void setup()
{
    WiFi.mode(WIFI_STA);
    Serial.begin(115200);
    IPAddress local_IP(192, 168, 1, 166);
    IPAddress gateway(192, 168, 1, 1);
    IPAddress subnet(255, 255, 255, 0);
    //设置
    bool bConfigSucessed = WiFi.config(local_IP, gateway, subnet); //设置静态IP
    Serial.print("Configuring WiFi");
    Serial.println(bConfigSucessed ? "sucessed" : "failed");
    // put your setup code here, to run once:
    String ssid = "ChinaNet-happy";
    String password = "359501300aa";

    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED)
    {
        delay(500);
    }
    Serial.println(WiFi.localIP());
    server.setNoDelay(true);
    server.begin();
}

void loop()
{
    static WiFiClient client = server.available();
    if (!client)
    {
        client = server.available();
    }
    if (!client)
    {
        return;
    }

    client.setNoDelay(true);
    String comdata = "";
    char buf[101];
    while (Serial.available() > 0) // 串口收到字符数大于零。
    {
        int size = Serial.read(buf, 100);
        buf[size] = '\0';
        comdata += buf;
        delay(2);
    }
    /******************串口打印数据************************/
    if (comdata != "") //如果接受到数据
    {
        //Serial.println(comdata);
        client.print(comdata);
        client.flush();
    }

    while (client.available())
    {
        //读取客户端发起的TCP请求
        unsigned char len = 0;
        size_t readsize = client.readBytes((char *)&len, 1);
        //Serial.println(readsize);
        //Serial.println(len);
        if (len > 200)
        {
            client.stop();
            return;
        }
        char *buf = new char[len];
        readsize = client.readBytes(buf, len);
        buf[readsize] = '\0';
        String req = buf;
        delete[] buf;
        //Serial.println(req);
        if (req.startsWith("com:"))
        {
            //Serial.println("COM");
            String msg = req.substring(4);
            Serial.updateBaudRate(atoi(msg.c_str()));
        }
        else if (req.startsWith("send:"))
        {
            //Serial.println("SEND");
            String msg = req.substring(5);
            //Serial.println(msg.length());
            Serial.print(msg);
        }
    }
}
